//
//  LoginViewController.m
//  Mall
//
//  Created by 远之航 on 2018/12/3.
//  Copyright © 2018 远之航. All rights reserved.
//

#import "LoginViewController.h"
#import "MiMaDenghLuViewController.h"
#import "GXtabbarController.h"
#import "AppDelegate.h"
@interface LoginViewController ()<UITextFieldDelegate>{
    NSInteger time;
    NSString *uuid;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingScrollView *mainScrollView;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTf;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *codeTf;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *allViewHeight;

@property (nonatomic,strong) NSTimer *timer;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customNavBar.title = @"";
    
    [self.customNavBar wr_setBackgroundAlpha:0];
    
   
    if (@available(iOS 11.0, *)) {
        self.mainScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    _allViewHeight.constant = ScreenHeight;
    
    _topSpace.constant = StatusBarHeight+80;
    
    CAGradientLayer *gl1 = [CAGradientLayer layer];
    gl1.frame = CGRectMake(0,0,ScreenWidth,ScreenHeight);
    gl1.startPoint = CGPointMake(1, 0.3);
    gl1.endPoint = CGPointMake(1, 0.1);
    gl1.colors = @[(__bridge id)rgba(255, 255, 255, 1).CGColor, (__bridge id)rgba(203, 222, 255, 1).CGColor];
    gl1.locations = @[@(0), @(1.0f)];
   
    [_backView.layer insertSublayer:gl1 atIndex:0];
    
    [_phoneTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
   
}

//密码登录
- (IBAction)miMa:(id)sender {
    MiMaDenghLuViewController *miMa = [[MiMaDenghLuViewController alloc] init];
    [self pushViewController:miMa];
}

//验证码
- (IBAction)yanZhengMa:(UIButton *)sender {
    [self.view endEditing:YES];
    if(_phoneTf.text.length == 0){
        [ZZPUtils showWarning:_phoneTf.placeholder];
        return;
    }
    
    if(_phoneTf.text.length != 11){
        [ZZPUtils showWarning:@"请输入正确的手机号"];
        return;
    }
    
//    [CaptchaView showWithType:puzzle andView:self.view CompleteBlock:^(NSString * _Nonnull result) {
//
//        NSLog(@"===================%@",result);
//        
//        
//        if(result.length > 0){
//            
//
//            
//        }
//        
//    }];
    _codeBtn.userInteractionEnabled = NO;
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:_phoneTf.text forKey:@"telephone"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/sendMessageCode" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            if(self.timer != nil){
                [self.timer invalidate];
                self.timer = nil;
            }
            //启动一个定时器
            time = 60;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(operatePerSecond) userInfo:nil repeats:YES];
            
            uuid = GetHandleString([info objectForKey:@"data"], @"uuid");
        }else{
            _codeBtn.userInteractionEnabled = YES;
        }
    }];

}



 
//实现定时器中的方法
- (void)operatePerSecond {
    if (time == 1) {
      [self.timer invalidate];
      time = 60;
      [self.codeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
      self.codeBtn.userInteractionEnabled = YES;
    }else {
      time --;
      [self.codeBtn setTitle:[NSString stringWithFormat:@"重试(%lds)" ,time] forState:UIControlStateNormal];
    }
}

-(void)textFieldDidChange:(UITextField *)textField
{
    CGFloat maxLength = 11;
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position || !selectedRange)
    {
        if (toBeString.length > maxLength)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:maxLength];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

//登录
- (IBAction)dengLu:(UIButton *)sender {
    [self.view endEditing:YES];
    
  
    
    if (_phoneTf.text.length == 0) {
        [ZZPUtils showWarning:_phoneTf.placeholder];
        return;
    }
    
    if (_codeTf.text.length == 0) {
        [ZZPUtils showWarning:_codeTf.placeholder];
        return;
    }
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:_phoneTf.text forKey:@"mobile"];
    [paraDic setValue:@"2" forKey:@"loginType"];
    [paraDic setValue:_codeTf.text forKey:@"smscode"];
    [paraDic setValue:uuid forKey:@"uuid"];
    [paraDic setValue:@"2" forKey:@"type"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/login" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSLog(@"%@",info);
            
            NSDictionary *data = [info objectForKey:@"data"];
            [ZZPUtils saveUserDefultsData:GetHandleString(data, @"adminToken") forKey:@"adminToken"];
            
            [self baoCunToken];
            
            [self getInfoFromServer];
        }
    }];
    
}

//新增或更新用户标识
- (void)baoCunToken{
    if([[ZZPUtils readUserDefultsDataForKey:@"deviceTokenString"] length] > 0){
        NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
        [paraDic setValue:@"2" forKey:@"deviceType"];
        [paraDic setValue:[ZZPUtils readUserDefultsDataForKey:@"deviceTokenString"] forKey:@"deviceToken"];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/adminUmeng/deviceToken" andParas:paraDic andShowHud:NO andTransferGottenData:^(id info, NSError *error) {
            if (!error) {
                NSLog(@"info:%@",info);
            }
        }];
    }
}

- (void)getInfoFromServer{
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/adminUser/queryLoginUser" andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSLog(@"%@",info);
            
            [ZZPUtils saveUserDefultsData:[ZZPUtils deleteEmpty:[info objectForKey:@"data"]] forKey:@"userInfo"];
            
            GXtabbarController *tabBarCtn=[[GXtabbarController alloc]init];
            [AppDelegate shareInstance].tabBarController = tabBarCtn;
            [AppDelegate shareInstance].window.rootViewController = tabBarCtn;
        }
    }];
}





@end



